﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace TCPTest
{
    class TCP
    {
        public const string WELCOME = "WELCOME\r\n";
        public const string ILLEGAL = "ILLEGAL\r\n";
        public const string OK = "OK\r\n";

        public static void RespondToClient(NetworkStream stream, string response)
        {
            byte[] bytes = GetBytes(response);
            stream.Write(bytes, 0, bytes.Length);
            stream.FlushAsync();
        }

        public static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        public static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

        public static  string GetNextLineFromClient(NetworkStream stream)
        {
            string stringData = "";
            byte[] data = new byte[1024];
            while (!stringData.EndsWith("\n"))
            {
                data = new byte[1024];
                int numBytesRead = stream.Read(data, 0, data.Length);
                stringData += Encoding.ASCII.GetString(data, 0, numBytesRead);
            }
            stringData = stringData.Trim();
            stringData = stringData.ToLower();
            stringData = stringData.TrimEnd(new char[] { '\n', '\r' });
            return stringData;
        }
    }
}
